<template>
  <!--库存-->
  <div class="inv" v-loading="loading">
    <!--仓库标签页-->
    <el-row>
      <el-tabs v-model="warehouseValue" @tab-click="changeWar(warehouseValue)">
        <el-tab-pane label="全部仓库" name="0"></el-tab-pane>
        <el-tab-pane :key="index" v-for="(item, index) in warehouseList" :label="item.warehouseName"
          :name="item.warehouseId+''">
        </el-tab-pane>
      </el-tabs>
    </el-row>
    <!--库存查找-->
    <el-row>
      <span style="padding: 0 10px"><i class="font-14 el-icon-s-open"></i></span>
      <el-select v-model="filterValue" placeholder="全部数据" style="width: 120px">
        <el-option v-for="item in filterOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <span style="padding: 0 10px 0 30px"><i class="fn el-icon-message-solid"></i></span>
      <el-input v-model="content" clearable placeholder="请输入内容" style="width: 150px"></el-input>
      <el-select v-model="vagueValue" placeholder="产品名" style="width: 120px">
        <el-option v-for="item in vagueOptions" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <el-button @click="initData(currPage,pageSize,warId,content)" icon="el-icon-search" size="small" circle></el-button>
    </el-row>
    <!--库存数据整理-->
    <div style="margin-top: 15px;overflow: hidden;">
      <el-col :span="12">
        <span set-lan="html:销售机会">库存</span>
        <small class="text-muted font-13">共{{totalSize}}条</small>
      </el-col>
      <el-col :span="12" class="col-sm-6 text-right m-b-10">
        <el-button @click="dialogOperation = true">数据整理</el-button>
      </el-col>
      <!--库存dialog-->
      <el-dialog title="库存" :visible.sync="dialogFormVisible"  @open="openDialog" @close="closeDialog" width="60%" style="color: #333333"  >
        <el-form :model="inventory" label-width="100px">
          <el-divider><span class="font-14-bold"></span></el-divider>
          <el-row>
            <el-col :span="12">
              <el-form-item label="仓库:">
                <div class="border-bo-s">{{inventory.warehouseByWarehouseId.warehouseName}}</div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="仓库:">
                <div class="border-bo-s">{{inventory.warehouseByWarehouseId.warehouseName}}</div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="产品名称:">
                <div class="border-bo-s">
                  <div class="border-bo-m">
                    {{inventory.productByProductId.productName}}
                    <el-tooltip class="item" effect="dark" content="打开详细页面" placement="bottom">
                      <router-link :to="{path:'/productview',query: {productId: inventory.productByProductId.productId}}">
                        <span style="color: #333333"><i class="el-icon-s-cooperation"></i></span>
                      </router-link>
                    </el-tooltip>
                  </div>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数量:">
                <div class="border-bo-s">{{inventory.inventoryNum}}</div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>
      <!--操作dialog-->
      <el-dialog title="操作" :visible.sync="dialogOperation" width="60%" style="color: #333333"  >
        <el-form label-width="100px">
          <el-divider><span class="font-14-bold"></span></el-divider>
          <el-row>
            <el-col>
              <el-form-item label="注意:">
                <br/>
                <div class="border-bo-s"><span>1.本操作会将自动删除数量为0库存数据。</span></div>
                <div class="border-bo-s"><span>1.本操作会对所有的仓库执行清理。</span></div>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" :offset="7">
              <el-form-item>
                <el-button @click="cleanInventory" type="primary">执行</el-button>
                <el-button @click="dialogOperation = false">取消</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-dialog>
    </div>
    <!--库存表格-->
    <el-table ref="multipleTable" :data="inventoryList" tooltip-effect="dark" id="outTable"
              :header-cell-style="rowClass" style="width: 100%" border >
      <el-table-column prop="inventoryId" label="ID" wsortable sortable></el-table-column>
      <el-table-column label="产品名称" >
        <template slot-scope="scope">
          <span>{{scope.row.productByProductId.productName}}</span>
          <el-tooltip class="item" effect="dark" content="打开详细页面" placement="bottom">
            <router-link :to="{path:'/productview',query: {productId: scope.row.productByProductId.productId}}">
              <span style="color: #333333"><i class="el-icon-s-cooperation"></i></span>
            </router-link>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="inventoryNum" label="数量" ></el-table-column>
      <el-table-column prop="warehouseByWarehouseId.warehouseName" label="仓库" >
      </el-table-column>
      <el-table-column prop="" label="操作" width="105px">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="查看" placement="bottom">
            <el-button size="mini" @click="handleEdit(scope.row)"
                       icon="el-icon-s-ticket" type="primary" circle style="margin-left: 10px"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-row style="margin-top:10px">
      <el-col :offset="8" :span="14">
        <el-pagination layout="sizes,prev,pager, next, jumper" :total="totalSize" @current-change="changePage"
                       :current-page.sync="currPage" :page-size="pageSize" :page-sizes="pageSizes" @size-change="changeSize"></el-pagination>
      </el-col>
      <el-col :span="2">
        <el-tooltip class="item" effect="dark" content="打印列表" placement="bottom">
          <el-button @click="handleWindowPrint('#outTable', '列表打印')" style="padding: 12px 12px" type="info" plain  icon="el-icon-printer"></el-button>
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="导出Excel格式数据" placement="bottom">
          <el-button @click="exportExcel" style="padding: 12px 12px" type="info" plain  icon="el-icon-document-remove"></el-button>
        </el-tooltip>
      </el-col>
    </el-row>
    <!-- 统计-->
    <el-row>
      <el-col :span="8">
        <div class="font-14-bold" style="margin: 30px 0 0 30px">分布</div>
        <div style="width: 400px;height:400px;margin: 20px auto 0px" ref="pieCharts"></div>
        <div style="margin-left: 30px">
          <el-select v-model="pieValue" @change="changePie(pieValue)" placeholder="未选" style="width: 350px">
            <el-option v-for="item in pieOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="font-14-bold" style="margin: 30px 0 0 30px">Top</div>
        <div style="width: 400px;height:400px;margin: 20px auto 0px" ref="columnarCharts"></div>
        <div style="margin-left: 30px">
          <el-select v-model="columnarValue" @change="changeColumnar(columnarValue)" placeholder="未选" style="width: 350px">
            <el-option v-for="item in columnarOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="font-14-bold" style="margin: 30px 0 0 30px">工具</div>
        <div style="width: 400px;height:400px;margin: 20px auto 0px" ref="lineCharts"></div>
        <div style="margin-left: 30px">
          <el-select v-model="lineValue" @change="changeLine(lineValue)" placeholder="未选" style="width: 350px">
            <el-option v-for="item in lineOptions" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </div>
      </el-col>
    </el-row>
  </div>

</template>

<script>
  import XLSX from "xlsx";
  import FileSaver from "file-saver";

  export default {
  data () {
    return {
      dialogFormVisible:false,
      dialogOperation:false,
      emp:{},
      inventoryList: [], // 库存集合分页
      warehouseList: [],// 仓库集合
      warehouseValue: '0',
      warId:0,// 默认仓库值
      pageSize: 10, // 分页页大小
      pageSizes:[10,20,30],//页大小数组
      currPage: 1, // 当前页码，默认为1
      totalSize: 0, // 总记录数
      inventory: {
        inventoryId: 0,
        inventoryNum: '',
        warehouseByWarehouseId: '',
        productByProductId: '',
      },
      content: '',// 按产品查询内容绑定值
      loading:false,
      filterOptions: [{
        value: 1,
        label: '全部数据'
      }],
      filterValue: 1,
      vagueOptions: [{
        value: 1,
        label: '产品名'
      }],
      vagueValue: 1,
      pieOptions: [{
        value: 1,
        label: '仓库产品数量分布'
      },{
        value: 2,
        label: '仓库产品种类分布'
      },{
        value: 3,
        label: '库存流水产品数量分布'
      }, {
        value: 4,
        label: '库存流水操作次数分布'
      }],
      pieValue: 1,
      pieList:[],
      pieDataList: [],
      pieNumList: [],
      columnarOptions: [{
        value: 1,
        label: '入库月度仓库产品总数'
      }],
      columnarValue: 1,
      columnarList: [],
      columnarDataList: [],
      columnarNumList: [],
      lineOptions: [{
        value: 1,
        label: '入库月度仓库产品总数'
      }],
      lineValue: 1,
      lineList: [],
      lineDataList: [],
      lineNumList: []
    }
  },
  methods: {
    // 查询当前员工
    loginEmp(){
      this.$axios.get('http://localhost:8088/emp')
        .then(v => {
          this.emp = v.data
        })
        .catch(function (v) {})
    },
    // 分页查询所有库存
    initData (currPage, pageSize,warId,content) {
      this.$axios.get('http://localhost:8088/inv-list', {
        params: {
          page: currPage,
          size: pageSize,
          warId:warId,
          content:content
        }
      })
        .then(v => {
          this.inventoryList = v.data.rows
          this.totalSize = v.data.total
        })
        .catch(function (v) {})
    },
    // 库存表格分页
    changePage (val) {
      // val就是当前页码
      this.initData(val, this.pageSize,this.warId)
    },
    //改变页大小
    changeSize(val){
      this.pageSize = val
      this.currPage = 1
      this.initData(this.currPage, this.pageSize,this.warId,this.content)
    },
    // 查询所有库存
    findWarehouse () {
      this.$axios.get('http://localhost:8088/war-list',)
        .then(v => {
          this.warehouseList = v.data
        })
        .catch(function (v) {})
    },
    // 修改数据回显
    handleEdit (val) {
      this.dialogFormVisible = true
      this.inventory.inventoryId = val.inventoryId
      this.inventory.inventoryNum = val.inventoryNum
      this.inventory.warehouseByWarehouseId = val.warehouseByWarehouseId
      this.inventory.productByProductId = val.productByProductId
    },
    // 打开dialog事件
    openDialog () {
    },
    // 关闭dialog事件
    closeDialog () {
      this.inventory= {
        inventoryId: 0,
        inventoryNum: '',
        warehouseByWarehouseId: '',
        productByProductId: '',
      }
    },
    // 选择仓库
    changeWar(val){
      this.warId = Number(val)
      this.initData(this.currPage,this.pageSize,this.warId,this.content)
    },
    // 清理仓库
    cleanInventory(){
      this.loading = true
      setTimeout(() => {
        this.loading = false;
      }, 1500)
      this.inventoryList.forEach(val => {
        if(val.inventoryNum === 0){
            this.deleteInventory(val.inventoryId)
        }
      })
      this.dialogOperation = false
    },
    // 删除axias
    deleteInventory(val){
      this.$axios.post('http://localhost:8088/delete-inventory',
        this.qs.stringify({invId: val}))
        .then(v => {
          this.initData(this.currPage,this.pageSize,this.warId,this.content)
        })
        .catch(function (v) {})
    },
    // 切换饼状图
    changePie (val){
      this.pieDataList = []
      this.pieNumList = []
      if (val === 1){
        this.inventoryCountData()
      }else if (val === 2){
        this.inventorySortData()
      }else if (val === 3){
        this.inventoryFlowCountData()
      }else if (val === 4){
        this.inventoryFlowOperationData()
      }
    },
    // 查询数据-仓库产品数量分布
    inventoryCountData() {
      this.$axios.get('http://localhost:8088/compute-inventory-count')
        .then(v => {
          this.pieList = v.data
          //计算
          this.computeInventoryCount()
        })
        .catch(function (v) {})
    },
    // 计算-仓库产品数量分布
    computeInventoryCount (){
      for(let i=0;i<this.pieList.length;i++) {
        this.pieDataList.push(this.pieList[i].datas);
        this.pieNumList.push({value:this.pieList[i].num,name:this.pieList[i].datas})
      }
    },
    // 查询数据-仓库产品种类分布
    inventorySortData() {
      this.$axios.get('http://localhost:8088/compute-inventory-sort')
        .then(v => {
          this.pieList = v.data
          //计算
          this.computeInventorySort()
        })
        .catch(function (v) {})
    },
    // 计算-仓库产品种类分布
    computeInventorySort (){
      for(let i=0;i<this.pieList.length;i++) {
        this.pieDataList.push(this.pieList[i].datas);
        this.pieNumList.push({value:this.pieList[i].num,name:this.pieList[i].datas})
      }
    },
    // 查询数据-库存流水产品数量分布
    inventoryFlowCountData() {
      this.$axios.get('http://localhost:8088/compute-inventory-flow-count')
        .then(v => {
          this.pieList = v.data
          //计算
          this.computeInventoryFlowCount()
        })
        .catch(function (v) {})
    },
    // 计算-库存流水产品数量分布
    computeInventoryFlowCount (){
      for(let i=0;i<this.pieList.length;i++) {
        if (this.pieList[i].datas === 1){
          this.pieDataList.push('入库');
          this.pieNumList.push({value:this.pieList[i].num,name:'入库'})
        }else if(this.pieList[i].datas === 2){
          this.pieDataList.push('出库');
          this.pieNumList.push({value:this.pieList[i].num,name:'出库'})
        }
      }
    },
    // 查询数据-库存流水操作次数分布
    inventoryFlowOperationData() {
      this.$axios.get('http://localhost:8088/compute-inventory-flow-ope')
        .then(v => {
          this.pieList = v.data
          //计算
          this.computeInventoryFlowOperation()
        })
        .catch(function (v) {})
    },
    // 计算-库存流水操作次数分布
    computeInventoryFlowOperation (){
      for(let i=0;i<this.pieList.length;i++) {
        if (this.pieList[i].datas === 1){
          this.pieDataList.push('入库');
          this.pieNumList.push({value:this.pieList[i].num,name:'入库'})
        }else if(this.pieList[i].datas === 2){
          this.pieDataList.push('出库');
          this.pieNumList.push({value:this.pieList[i].num,name:'出库'})
        }
      }
    },
    // 饼状图
    pieCharts () {
      let myChart = this.$echarts.init(this.$refs.pieCharts)
      // 绘制图表
      myChart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          // orient: 'vertical',
          // top: 'middle',
          bottom: 10,
          left: 'center',
          data: this.pieDataList
        },
        series: [
          {
            type: 'pie',
            radius: '65%',
            center: ['50%', '50%'],
            selectedMode: 'single',
            data: this.pieNumList,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      })
    },
    // 切换柱状图
    changeColumnar(val){
      this.columnarDataList = []
      this.columnarNumList = []
      if (val === 1){
        this.inventoryFlowIntoMonthData()
      }else if(val === 2){

      }else if(val === 3){

      }else if(val === 4){
      }
    },
    // 查询数据-入库月度仓库产品总数
    inventoryFlowIntoMonthData() {
      this.$axios.get('http://localhost:8088/compute-inventory-flow-into-month')
        .then(v => {
          this.columnarList = v.data
          //计算
          this.computeInventoryFlowIntoMonth()
        })
        .catch(function (v) {})
    },
    // 计算-入库月度仓库产品总数
    computeInventoryFlowIntoMonth (){
      for(let i=0;i<this.columnarList.length;i++) {
        this.columnarDataList.push(this.columnarList[i].datas);
        this.columnarNumList.push(this.columnarList[i].num)
      }
    },
    // 柱状图
    columnarCharts (){
      let myChart = this.$echarts.init(this.$refs.columnarCharts)
      // 绘制图表0
      myChart.setOption({
        color: ['#3398DB'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: this.columnarDataList,
            /* (function(){
               this.findDateData()
               let arr=[];
               for(let i=0;i<this.findDateList.length;i++){
                 arr.push(this.findDateList[i].dates);
               }
               return arr;
             })(),*/
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: this.columnarName,
            type: 'bar',
            barWidth: '60%',
            data: this.columnarNumList,
          }
        ]
      })
    },
    // 切换折线图
    changeLine(val){
      this.lineDataList = []
      this.lineNumList = []
      if (val === 1){
        this.inventoryFlowIntoMonthData2()
      }else if(val === 2){

      }else if(val === 3){

      }else if(val === 4){

      }
    },
    // 查询数据-入库月度仓库产品总数
    inventoryFlowIntoMonthData2() {
      this.$axios.get('http://localhost:8088/compute-inventory-flow-into-month')
        .then(v => {
          this.lineList = v.data
          //计算
          this.computeInventoryFlowIntoMonth2()
        })
        .catch(function (v) {})
    },
    // 计算-入库月度仓库产品总数
    computeInventoryFlowIntoMonth2 (){
      for(let i=0;i<this.lineList.length;i++) {
        this.lineDataList.push(this.lineList[i].datas);
        this.lineNumList.push(this.lineList[i].num)
      }
    },
    //折线图
    lineCharts (){
      let myChart = this.$echarts.init(this.$refs.lineCharts)
      // 绘制图表0
      myChart.setOption({
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['状态']
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.lineDataList
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}'
          }
        },
        series: [
          {
            name: '金额￥',
            type: 'line',
            data: this.lineNumList,
            markPoint: {
              data: [
                {type: 'max', name: '最大值'},
                {type: 'min', name: '最小值'}
              ]
            },

          }
        ]
      })
    },
    // pdf打印
    handleWindowPrint (ele, fileName) {
      document.body.innerHTML = document.querySelector(ele).outerHTML
      // 转异步 等待dom元素渲染（样式）完毕在打印
      setTimeout(() => {
        // 打印
        window.print()
        // 刷新页面
        window.location.reload()
      }, 20)
    },
    //导出excel
    exportExcel () {
      var xlsxParam = { raw: true };//转换成excel时，使用原始的格式
      var wb = XLSX.utils.table_to_book(document.querySelector("#outTable"),xlsxParam);
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array"
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream;charset=utf-8" }),
          "库存导出.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
    // 表头靠左样式
    rowClass(){
      return "text-align:left"
    },
  },
  created() {
    this.loginEmp()
    this.initData(this.currPage,this.pageSize,this.warId,this.content)
    this.findWarehouse()
    this.inventoryCountData()
    this.inventoryFlowIntoMonthData()
    this.inventoryFlowIntoMonthData2()
  },
  updated() {
    this.pieCharts()
    this.columnarCharts()
    this.lineCharts()
  },
  watch:{
    pieList(val){
      this.pieCharts()
    },
    columnarList(val) {
      this.columnarCharts()
    },
    lineList(val){
      this.lineCharts()
    }
  }
}
</script>

<style>
</style>
